<template>
    <div>
        <el-dialog :title="title" :visible.sync="showDialog" width="55%" :before-close="beforeClose" :close-on-click-modal="false">
            <div class="dialog-container">
                <template v-if="dialogType == 'form'">
                    <el-form ref="form" :model="form" label-width="160px" v-if="showDialog" :rules="rules">
                        <el-form-item label="活动名称:" prop="name">
                            <el-input maxlength="20" v-model.trim="form.name" placeholder="请输入活动名称" :disabled="onlyRead" />
                        </el-form-item>
                        <el-form-item label="排序:" prop="sort">
                            <el-input-number v-model="form.sort" :min="0" :max="100" label="请输入排序" :disabled="onlyRead"></el-input-number>
                        </el-form-item>
                        <el-form-item label="活动时间:" prop="time">
                            <el-date-picker
                                :disabled="onlyRead"
                                v-model="form.time"
                                type="datetimerange"
                                value-format="yyyy-MM-dd HH:mm:ss"
                                :picker-options="pickerOptions"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                            ></el-date-picker>
                        </el-form-item>
                        <el-form-item label="活动广告图:" prop="image1">
                            <div class="show-image">
                                <div class="up-image" v-if="form.image1">
                                    <i v-if="!onlyRead" class="el-icon-circle-close" @click="deleteImage(1)"></i>
                                    <img :src="form.image1" alt />
                                    <el-button v-if="!onlyRead" type="primary" @click="chooseImage(1)">重新上传</el-button>
                                </div>
                                <div class="add-image" v-else @click="chooseImage(1)">
                                    <i class="el-icon-plus icon-plus"></i>
                                </div>
                                <div class="image-info">
                                    <span>上传提示:</span>
                                    <span>广告图限制 </span>
                                    <span>宽:343像素</span>
                                    <span>高:88像素</span>
                                    <span>格式:bmp、jpg、png</span>
                                </div>
                            </div>
                        </el-form-item>
                        <el-form-item label="活动引导图:">
                            <div class="show-image">
                                <div class="up-image" v-if="form.image2">
                                    <i v-if="!onlyRead" class="el-icon-circle-close" @click="deleteImage(2)"></i>
                                    <img :src="form.image2" alt />
                                    <el-button v-if="!onlyRead" type="primary" @click="chooseImage(2)">重新上传</el-button>
                                </div>
                                <div class="add-image" v-else @click="chooseImage(2)">
                                    <i class="el-icon-plus icon-plus"></i>
                                </div>
                                <div class="image-info">
                                    <span>上传提示:</span>
                                    <span>广告图限制 </span>
                                    <span>大小:5M以内</span>
                                    <span>格式:bmp、jpg、png</span>
                                </div>
                            </div>
                        </el-form-item>
                        <el-form-item label="活动链接" prop="url">
                            <el-input :disabled="onlyRead" v-model.trim="form.url" placeholder="链接地址请以http或https开头" maxlength="300" style="width: 350px" />
                        </el-form-item>
                        <el-form-item label="活动描述:" prop="desc1" key="desc1">
                            <el-input :disabled="onlyRead" type="textarea" v-model.trim="form.desc1" placeholder="请输入活动描述" style="width: 350px" />
                        </el-form-item>
                        <el-form-item label="活动可见范围:" prop="deptIds">
                            <el-button type="primary" @click="selectDepart">{{ onlyRead ? '查看（部门/条线）' : '请选择/编辑可见范围（部门/条线）' }}</el-button>
                        </el-form-item>
                    </el-form>
                    <span slot="footer" class="dialog-footer">
                        <el-button :type="onlyRead ? 'primary' : ''" @click="beforeClose">{{ onlyRead ? '确 定' : '取 消' }}</el-button>
                        <el-button :loading="btnloading" v-if="!onlyRead" type="primary" @click="updateProduct">确 定</el-button>
                    </span>
                </template>
                <template v-else>
                    <el-tree ref="tree" :data="departTree" show-checkbox node-key="id" :default-checked-keys="form.deptIds" :props="defaultProps"></el-tree>
                    <span slot="footer" class="dialog-footer">
                        <el-button :type="onlyRead ? 'primary' : ''" @click="dialogType = 'form'">{{ onlyRead ? '确 定' : '取 消' }}</el-button>
                        <el-button :loading="btnloading" v-if="!onlyRead" type="primary" @click="getCheckedNodes">确 定</el-button>
                    </span>
                </template>
            </div>
        </el-dialog>
        <input type="file" ref="upfileInput" @change="uploadFile" accept="image/jpg, image/jpeg, image/png, image/gif" hidden />
    </div>
</template>
<script>
import { fetchTree } from '@/api/admin/dept';
import { upload } from '@/api/customer-into/verbal-manage';
import storeApi from '@/api/store/store.js';
export default {
    props: {
        showDialog: {
            type: Boolean,
            default: false
        },
        dialogTitle: {
            type: String,
            default: ''
        },
        dialogInfo: {
            type: Object,
            default: () => {
                return {
                    name: '',
                    sort: 0,
                    time: null,
                    image1: '',
                    image2: '',
                    url: '',
                    desc1: ''
                };
            }
        },
        onlyRead: {
            type: Boolean,
            default: false
        }
    },
    data() {
        let validatorTime = (rule, value, callback) => {
            if (this.form.time) {
                callback();
            } else {
                callback('请选择活动时间');
            }
        };
        let validatorDeptIds = (rule, value, callback) => {
            if (this.form.deptIds && this.form.deptIds.length > 0) {
                callback();
            } else {
                callback('请选择活动可见范围');
            }
        };
        return {
            // 部门树
            departTree: [],
            // 时间限制
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() < Date.now() - 8.64e7;
                }
            },
            // 树组件props
            defaultProps: {
                children: 'children',
                label: 'name',
                disabled: this.isdisabledFn
            },
            // 表单对象
            form: {
                name: '',
                sort: 0,
                time: null,
                image1: '',
                image2: '',
                url: '',
                loanDescType: 2,
                type: 2
            },
            // 弹窗标题
            title: '',
            // 视图类型
            dialogType: 'form',
            // 表单校验
            rules: {
                name: [
                    {
                        required: true,
                        message: '活动名称不能为空',
                        trigger: 'blur'
                    }
                ],
                sort: [
                    {
                        required: true,
                        message: '请输入排序',
                        trigger: 'change'
                    }
                ],
                time: [{ required: true, validator: validatorTime }],
                image1: [{ required: true, message: '请选择活动广告图', trigger: 'change' }],
                url: [{ pattern: /^((http|https):\/\/)+([\w\-])/, message: '请输入以http或https必须为开头的正确链接' }, { max: 300, min: 1, message: '链接长度不超过300个字符' }],
                desc1: [{ required: true, message: '活动描述不能为空' }, { max: 20, min: 1, message: '活动描述不超过200个字符' }],
                deptIds: [{ required: true, validator: validatorDeptIds }]
            },
            // loading
            btnloading: false
        };
    },
    watch: {
        showDialog: {
            handler(val) {
                if (val) {
                    this.form = JSON.parse(JSON.stringify(this.dialogInfo));
                    if (this.dialogInfo.startTime && this.dialogInfo.endTime) {
                        this.form.time = [this.dialogInfo.startTime, this.dialogInfo.endTime];
                    }
                    this.title = JSON.parse(JSON.stringify(this.dialogTitle));
                    this.dialogType = 'form';
                }
            }
        }
    },
    methods: {
        // 是否禁用
        isdisabledFn() {
            if (this.onlyRead) {
                return true;
            }
            return false;
        },
        // 查询部门树
        selectDepart() {
            this.title = '选择可见范围';
            this.dialogType = 'tree';
            fetchTree().then((res) => {
                this.departTree = res.data.data;
            });
        },
        // 弹框关闭前的操作
        beforeClose() {
            if (this.dialogType == 'tree') {
                this.dialogType = 'form';
            } else {
                this.$emit('handleClose');
            }
        },
        // 上传文件
        uploadFile(e) {
            let files = e.target.files[0];
            if (files.size / 1024 / 1024 > 5) {
                var file = this.$refs.upfileInput;
                file.value = ''; //虽然file的value不能设为有字符的值，但是可以设置为空值
                return this.$message.warning('该图片超过5M不能上传');
            }
            let param = new FormData();
            // 将得到的文件流添加到FormData对象
            param.append('file', files);
            upload(param).then((res) => {
                let fileList = res.data.data;
                this.$set(this.form, `image${this.imageType}`, fileList.url);
                this.$refs.form.clearValidate([`image${this.imageType}`]);
            });
            var file = this.$refs.upfileInput;
            file.value = ''; //虽然file的value不能设为有字符的值，但是可以设置为空值
        },
        // 删除图片
        deleteImage(type) {
            this.form[`image${type}`] = '';
        },
        // 选择图片
        chooseImage(type) {
            if (this.onlyRead) return;
            this.imageType = type;
            this.$refs.upfileInput.click();
        },
        // 点击弹窗确定 更新活动数据
        updateProduct() {
            this.$refs.form.validate((valid) => {
                if (valid) {
                    if (this.form.deptIds && this.form.deptIds.length < 1) return this.$message.warning('请选择可见范围');
                    this.form.startTime = this.form.time[0];
                    this.form.endTime = this.form.time[1];
                    if (!this.form.url) delete this.form.url;
                    if (this.form.id) {
                        // 编辑
                        this.handleSubmit(this.form, 2);
                    } else {
                        // 新增
                        this.handleSubmit(this.form, 1);
                    }
                }
            });
        },
        // 新增、编辑活动
        handleSubmit(params, type) {
            params.startTime = params.time[0];
            params.endTime = params.time[1];
            let obj = JSON.parse(JSON.stringify(params));
            delete obj.time;
            this.btnloading = true;
            if (type == 1) {
                storeApi.addProduct(obj).then((res) => {
                    this.btnloading = false;
                    if (res.data.code != 0) return;
                    this.$message.success('新增成功');
                    this.$emit('handleUpdate');
                });
            } else {
                storeApi.editProduct(obj).then((res) => {
                    this.btnloading = false;
                    if (res.data.code != 0) return;
                    this.$message({
                        type: 'success',
                        message: '修改成功'
                    });
                    this.$emit('handleUpdate');
                });
            }
        },
        // 获取所有选中的部门id
        getCheckedNodes() {
            if (!this.onlyRead) {
                let checkIds = this.$refs.tree.getCheckedKeys();
                if (checkIds.length < 1) return this.$message.warning('请选择可见范围');
                this.form.deptIds = checkIds;
                this.dialogType = 'form';
            }
        }
    }
};
</script>
<style scoped lang="scss">
.dialog-container {
    text-align: right;
}
/deep/.el-form-item__content {
    display: flex;
    align-items: center;
}
/deep/.el-tree-node__content {
    height: 25px !important;
}
/deep/.el-input-number--medium {
    .el-input-number__increase {
        right: 1px !important;
    }
    .el-input-number__decrease {
        left: 2px !important;
    }
}

.show-image {
    display: flex;
    flex-wrap: wrap;
    .add-image {
        width: 120px;
        height: 120px;
        display: flex;
        justify-content: center;
        align-items: center;
        border-radius: 5px;
        border: 1px solid #eee;
        .icon-plus {
            font-size: 30px;
        }
    }
    .up-image {
        position: relative;
        display: flex;
        flex-direction: column;
        align-items: center;
        margin-right: 10px;
        .el-icon-circle-close {
            position: absolute;
            top: -5px;
            right: -5px;
            background: #fff;
            z-index: 97;
        }
        img {
            width: 120px;
            height: 120px;
            border: 1px solid #eee;
        }
        button {
            margin-top: 15px;
        }
    }
    .add-image:hover {
        cursor: pointer;
    }
    .image-info {
        margin-left: 10px;
        display: flex;
        flex-direction: column;
        span {
            text-align: left;
            line-height: 24px;
        }
    }
}
</style>
